package org.madgecko.basic.dao.impl;

import org.madgecko.basic.dao.BaseDao;
import org.madgecko.basic.dao.iface.IModuleDao;
import org.madgecko.basic.model.Module;
import org.madgecko.basic.model.Role;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class ModuleDao extends BaseDao<Module> implements IModuleDao {
    @Override
    public List<Module> listAllModule() {
        //1条sql,尽管有parent级联，但sql只有一条
		String hql = "from Module order by orderNum";
        return this.list(hql);
    }

    @Override
    public List<Module> listModuleByRoles(List<Integer> roleIds){
	    if(roleIds.size()==0){
		    return new ArrayList<Module>();
	    }
	    //TODO 多条sql 待观察
	    String ids = "(";
	    for(Integer id : roleIds){
		    ids += id + ", ";
	    }
	    ids = ids.substring(0, ids.length()-2);
	    ids += ")";
        String hql = "select distinct rc.command.module from RoleCommand rc where rc.command.module.status=1 and rc.role.id in " + ids + " order by rc.command.module.orderNum" ;
	    return this.list(hql);
    }

	@Override
	public List<Module> listModuleByParent(int parentId) {
		String hql = "from Module m where m.parent.id=? order by m.orderNum";
		return this.list(hql, parentId);
	}

    @Override
    public void deleteByParent(Integer parentId) {
        String hql = "DELETE FROM Module m WHERE m.parent.id=" + parentId;
        this.updateByHql(hql);
    }

    @Override
    public List<Integer> listIdsByParent(Integer parentId){
        String hql = "SELECT m.id FROM Module m WHERE m.parent.id=" + parentId;
        return this.listIdByHql(hql);
    }

}
